package org.glow.changgou.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glow.changgou.entity.IdWorker;
import org.glow.changgou.goods.feign.SkuFeign;
import org.glow.changgou.order.dao.OrderItemMapper;
import org.glow.changgou.order.dao.OrderMapper;
import org.glow.changgou.order.pojo.Order;
import org.glow.changgou.order.pojo.OrderItem;
import org.glow.changgou.order.pojo.OrderLog;
import org.glow.changgou.order.service.CartService;
import org.glow.changgou.order.service.OrderService;
import org.glow.changgou.user.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/****
 * @Author:glow
 * @Description:Order业务层接口实现类
 *****/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper,Order> implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartService cartService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserFeign userFeign;
    /**
     * Order条件+分页查询
     * @param order 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Order> findPage(Order order, int page, int size){
        Page<Order> pageInfo = new Page<>(page,size);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = getCondition(queryWrapper,order);
        return orderMapper.selectPage(pageInfo,queryWrapper);
    }

    /**
     * Order分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Order> findPage(int page, int size){
        Page<Order> pageInfo = new Page<>(page,size);

        return orderMapper.selectPage(pageInfo,null);
    }

    /**
     * Order条件查询
     * @param order
     * @return
     */
    @Override
    public List<Order> findList(Order order){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = getCondition(queryWrapper,order);
        return orderMapper.selectList(queryWrapper);
    }


    /**
     * Order构建查询对象
     * @param order
     * @return
     */
    public LambdaQueryWrapper<Order> getCondition(LambdaQueryWrapper<Order> queryWrapper, Order order){

        if(order!=null){
            // 订单id
            if(!StringUtils.isEmpty(order.getId())){
//                    criteria.andEqualTo("id",order.getId());
                    queryWrapper.eq(Order::getId,order.getId());
            }
            // 数量合计
            if(!StringUtils.isEmpty(order.getTotalNum())){
//                    criteria.andEqualTo("totalNum",order.getTotalNum());
                queryWrapper.eq(Order::getTotalNum,order.getTotalNum());
            }
            // 金额合计
            if(!StringUtils.isEmpty(order.getTotalMoney())){
//                    criteria.andEqualTo("totalMoney",order.getTotalMoney());
                queryWrapper.eq(Order::getTotalMoney,order.getTotalMoney());
            }
            // 优惠金额
            if(!StringUtils.isEmpty(order.getPreMoney())){
//                    criteria.andEqualTo("preMoney",order.getPreMoney());
                    queryWrapper.eq(Order::getPreMoney,order.getPreMoney());
            }
            // 邮费
            if(!StringUtils.isEmpty(order.getPostFee())){
//                    criteria.andEqualTo("postFee",order.getPostFee());
                    queryWrapper.eq(Order::getPostFee,order.getPostFee());
            }
            // 实付金额
            if(!StringUtils.isEmpty(order.getPayMoney())){
//                    criteria.andEqualTo("payMoney",order.getPayMoney());
                    queryWrapper.eq(Order::getPayMoney,order.getPayMoney());
            }
            // 支付类型，1、在线支付、0 货到付款
            if(!StringUtils.isEmpty(order.getPayType())){
//                    criteria.andEqualTo("payType",order.getPayType());
                    queryWrapper.eq(Order::getPayType,order.getPayType());
            }
            // 订单创建时间
            if(!StringUtils.isEmpty(order.getCreateTime())){
//                    criteria.andEqualTo("createTime",order.getCreateTime());
                    queryWrapper.eq(Order::getCreateTime,order.getCreateTime());
            }
            // 订单更新时间
            if(!StringUtils.isEmpty(order.getUpdateTime())){
//                    criteria.andEqualTo("updateTime",order.getUpdateTime());
                    queryWrapper.eq(Order::getUpdateTime,order.getUpdateTime());
            }
            // 付款时间
            if(!StringUtils.isEmpty(order.getPayTime())){
//                    criteria.andEqualTo("payTime",order.getPayTime());
                    queryWrapper.eq(Order::getPayTime,order.getPayTime());
            }
            // 发货时间
            if(!StringUtils.isEmpty(order.getConsignTime())){
//                    criteria.andEqualTo("consignTime",order.getConsignTime());
                    queryWrapper.eq(Order::getConsignTime,order.getConsignTime());
            }
            // 交易完成时间
            if(!StringUtils.isEmpty(order.getEndTime())){
//                    criteria.andEqualTo("endTime",order.getEndTime());
                    queryWrapper.eq(Order::getEndTime,order.getEndTime());
            }
            // 交易关闭时间
            if(!StringUtils.isEmpty(order.getCloseTime())){
//                    criteria.andEqualTo("closeTime",order.getCloseTime());
                    queryWrapper.eq(Order::getCloseTime,order.getCloseTime());
            }
            // 物流名称
            if(!StringUtils.isEmpty(order.getShippingName())){
//                    criteria.andEqualTo("shippingName",order.getShippingName());
                    queryWrapper.eq(Order::getShippingName,order.getShippingName());
            }
            // 物流单号
            if(!StringUtils.isEmpty(order.getShippingCode())){
//                    criteria.andEqualTo("shippingCode",order.getShippingCode());
                    queryWrapper.eq(Order::getShippingCode,order.getShippingCode());
            }
            // 用户名称
            if(!StringUtils.isEmpty(order.getUsername())){
//                    criteria.andLike("username","%"+order.getUsername()+"%");
                    queryWrapper.like(Order::getUsername,order.getUsername());
            }
            // 买家留言
            if(!StringUtils.isEmpty(order.getBuyerMessage())){
//                    criteria.andEqualTo("buyerMessage",order.getBuyerMessage());
                    queryWrapper.eq(Order::getBuyerMessage,order.getBuyerMessage());
            }
            // 购买率
            if(!StringUtils.isEmpty(order.getBuyerRate())){
//                    criteria.andEqualTo("buyerRate",order.getBuyerRate());
                    queryWrapper.eq(Order::getBuyerRate,order.getBuyerRate());
            }
            // 收货人
            if(!StringUtils.isEmpty(order.getReceiverContact())){
                queryWrapper.eq(Order::getReceiverContact,order.getReceiverContact());
//                    criteria.andEqualTo("receiverContact",order.getReceiverContact());
            }
            // 收货人手机
            if(!StringUtils.isEmpty(order.getReceiverMobile())){
                queryWrapper.eq(Order::getReceiverMobile,order.getReceiverMobile());
//                    criteria.andEqualTo("receiverMobile",order.getReceiverMobile());
            }
            // 收货人地址
            if(!StringUtils.isEmpty(order.getReceiverAddress())){
                queryWrapper.eq(Order::getReceiverAddress,order.getReceiverAddress());
//                    criteria.andEqualTo("receiverAddress",order.getReceiverAddress());
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(!StringUtils.isEmpty(order.getSourceType())){
//                    criteria.andEqualTo("sourceType",order.getSourceType());
                    queryWrapper.eq(Order::getSourceType,order.getSourceType());
            }
            // 交易流水号
            if(!StringUtils.isEmpty(order.getTransactionId())){
//                    criteria.andEqualTo("transactionId",order.getTransactionId());
                    queryWrapper.eq(Order::getTransactionId,order.getTransactionId());
            }
            // 订单状态,0:未完成,1:已完成，2：已退货
            if(!StringUtils.isEmpty(order.getOrderStatus())){
//                    criteria.andEqualTo("orderStatus",order.getOrderStatus());
                    queryWrapper.eq(Order::getOrderStatus,order.getOrderStatus());
            }
            // 支付状态,0:未支付，1：已支付，2：支付失败
            if(!StringUtils.isEmpty(order.getPayStatus())){
//                    criteria.andEqualTo("payStatus",order.getPayStatus());
                    queryWrapper.eq(Order::getPayStatus,order.getPayStatus());
            }
            // 发货状态,0:未发货，1：已发货，2：已收货
            if(!StringUtils.isEmpty(order.getConsignStatus())){
//                    criteria.andEqualTo("consignStatus",order.getConsignStatus());
                    queryWrapper.eq(Order::getConsignStatus,order.getConsignStatus());
            }
            // 是否删除
            if(!StringUtils.isEmpty(order.getIsDelete())){
//                    criteria.andEqualTo("isDelete",order.getIsDelete());
                    queryWrapper.eq(Order::getIsDelete,order.getIsDelete());
            }
        }
        return queryWrapper;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        orderMapper.deleteById(id);
    }

    /**
     * 修改Order
     * @param order
     */
    @Override
    public void update(Order order){
        orderMapper.updateById(order);
    }

    /**
     *
     * 涉及多表操作，需要添加事务
     * 增加Order
     * @param order
     */
    @Transactional
    @Override
    public Order add(Order order){
        //查询出用户的所有购物车
        List<OrderItem> orderItems = cartService.list(order.getUsername());

        //统计计算
        int totalMoney = 0;
        int totalPayMoney=0;
        int num = 0;
        for (OrderItem orderItem : orderItems) {
            //总金额
            totalMoney+=orderItem.getMoney();

            //实际支付金额
            totalPayMoney+=orderItem.getPayMoney();
            //总数量
            num+=orderItem.getNum();
        }
        order.setTotalNum(num);
        order.setTotalMoney(totalMoney);
        order.setPayMoney(totalPayMoney);
        order.setPreMoney(totalMoney-totalPayMoney);

        //其他数据完善
        order.setCreateTime(new Date());
        order.setUpdateTime(order.getCreateTime());
        order.setBuyerRate("0");        //0:未评价，1：已评价
        order.setSourceType("1");       //来源，1：WEB
        order.setOrderStatus("0");      //0:未完成,1:已完成，2：已退货
        order.setPayStatus("0");        //0:未支付，1：已支付，2：支付失败
        order.setConsignStatus("0");    //0:未发货，1：已发货，2：已收货
        order.setId("NO."+idWorker.nextId());
        int count = orderMapper.insert(order);

        //添加订单明细
        for (OrderItem orderItem : orderItems) {
            orderItem.setId("NO."+idWorker.nextId());
            orderItem.setIsReturn("0");
            orderItem.setOrderId(order.getId());
            orderItemMapper.insert(orderItem);
        }
        //订单添加后，需要调用sku服务来删除库存
        skuFeign.decrCount(order.getUsername());
        //订单完成后，增加积分
        userFeign.addPoints(10);
        //订单存储在redis，用于线上支付
        if(order.getPayType().equalsIgnoreCase("1"))
        {
            redisTemplate.boundHashOps("Order").put(order.getId(),order);
        }
        //清除Redis缓存购物车数据
        redisTemplate.delete("Cart_"+order.getUsername());
        return order;
    }

    /**
     * 根据ID查询Order
     * @param id
     * @return
     */
    @Override
    public Order findById(String id){
        return  orderMapper.selectById(id);
    }

    /**
     * 查询Order全部数据
     * @return
     */
    @Override
    public List<Order> findAll() {
        return orderMapper.selectList(null);
    }

    /***
     * 订单修改
     * @param orderId
     * @param transactionid  微信支付的交易流水号
     */
    @Override
    public void updateStatus(String orderId,String transactionid) {
        //1.修改订单
        Order order = orderMapper.selectById(orderId);
        order.setUpdateTime(new Date());    //时间也可以从微信接口返回过来，这里为了方便，我们就直接使用当前时间了
        order.setPayTime(order.getUpdateTime());    //不允许这么写
        order.setTransactionId(transactionid);  //交易流水号
        order.setPayStatus("1");    //已支付
        orderMapper.updateById(order);

        //2.删除Redis中的订单记录
        redisTemplate.boundHashOps("Order").delete(orderId);
    }

    /***
     * 订单的删除操作
     */
    @Override
    public void deleteOrder(String id) {
        //改状态
        Order order = (Order) redisTemplate.boundHashOps("Order").get(id);
        order.setUpdateTime(new Date());
        order.setPayStatus("2");    //支付失败
        orderMapper.updateById(order);

        //删除缓存
        redisTemplate.boundHashOps("Order").delete(id);
    }
}
